package com.dqyy.order.task;

import com.dqyy.order.service.DatabaseBackupService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;

/**
 * 数据库备份任务类
 * 实现Quartz的Job接口，用于执行数据库备份和发送邮件的具体操作
 */
@Slf4j
@Component
public class DatabaseBackupTask implements Job {

    @Autowired
    private DatabaseBackupService databaseBackupService;

    /**
     * 执行数据库备份任务
     * 该方法会在配置的时间点自动执行
     * 
     * @param context JobExecutionContext对象，包含任务执行的上下文信息
     * @throws JobExecutionException 当任务执行失败时抛出异常
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("开始执行数据库备份任务");
        try {
            // 1. 执行数据库备份，获取备份文件
            File backupFile = databaseBackupService.backupDatabase();
            
            if (backupFile != null) {
                // 2. 如果备份成功，发送备份文件到邮箱
                boolean sent = databaseBackupService.sendBackupToEmail(backupFile);
                if (sent) {
                    log.info("数据库备份文件已成功发送到邮箱");
                } else {
                    log.error("数据库备份文件发送失败");
                }
            } else {
                log.error("数据库备份失败");
            }
        } catch (Exception e) {
            // 3. 记录异常信息并抛出
            log.error("数据库备份任务执行异常", e);
            throw new JobExecutionException(e);
        }
    }
} 